import { previewFeeApi } from "@/api/financialManagement/receivable";
import { computed, reactive, Ref, ref } from "vue";

export default function InitHook(state: { passData: Ref<ReceivableFee.ListRows[]> }) {
  const { passData } = state;
  const tableData = ref<Array<ReceivableFee.PreviewFeeListRows>>([]);
  const loading = ref<boolean>(false);
  const mergeCells = ref<Array<Base.GeneraDataType>>([]);
  const init = () => {
    loading.value = true;
    mergeCells.value = [];
    tableData.value = [];
    const params: any = {
      waybillNums: passData.value.map((t: ReceivableFee.ListRows) => t.waybillNum),
      ids: passData.value.map((t: ReceivableFee.ListRows) => t.id)
    };
    if (!params.waybillNums.length) {
      params.waybillNums = undefined;
    }

    if (!params.ids.length) {
      params.ids = undefined;
    }
    return previewFeeApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          // tableData.value = data || [];
          const cellMap: any = {};
          const dataMap: any = {};
          for (let i = 0; i < data.length; i++) {
            const target = data[i];
            if (dataMap[`${target.customerName},${target.waybillNum}`]) dataMap[`${target.customerName},${target.waybillNum}`].push(target);
            else dataMap[`${target.customerName},${target.waybillNum}`] = [target];
          }
          for (const key in dataMap) {
            tableData.value.push(...dataMap[key]);
          }
          for (let i = 0; i < tableData.value.length; i++) {
            const target = tableData.value[i];
            console.log(`${target.customerName},${target.waybillNum}`);
            if (cellMap[`${target.customerName},${target.waybillNum}`]) cellMap[`${target.customerName},${target.waybillNum}`].rowspan++;
            else
              cellMap[`${target.customerName},${target.waybillNum}`] = {
                row: i,
                col: 0,
                rowspan: 1,
                colspan: 1
              };
          }
          for (const key in cellMap) {
            mergeCells.value.push(cellMap[key]);
          }
        }
      })
      .finally(() => (loading.value = false));
  };
  const allAmount = computed<string>(() => {
    const amount = tableData.value.map((t: ReceivableFee.PreviewFeeListRows) => t.totalPrice || 0);
    return amount.reduce((a: number, b: number) => (a * 100 + b * 100) / 100, 0).toFixed(2);
  });
  const dialogOpts = reactive<Base.DialogOpts>({
    title: "",
    width: "520px",
    component: "",
    visible: false,
    type: 1,
    passData: {}
  });
  return {
    tableData,
    loading,
    init,
    allAmount,
    dialogOpts,
    mergeCells
  };
}
